package tongwentongshu.com.app;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import tongwentongshu.com.app.activity.BaseActivity;
import tongwentongshu.com.app.activity.DepositDetailsActivity;
import tongwentongshu.com.app.activity.PersonalCenterActivity;
import tongwentongshu.com.app.activity.ReadingDetailsActivity;
import tongwentongshu.com.app.activity.SearchActivity;
import tongwentongshu.com.app.activity.ShudouActivity;
import tongwentongshu.com.app.activity.WebViewActivity;
import tongwentongshu.com.app.activityim.HomeActivity;
import tongwentongshu.com.app.adapter.MainBooksAdapter;
import tongwentongshu.com.app.bean.BookListBean;
import tongwentongshu.com.app.bean.MessageEvent;
import tongwentongshu.com.app.bean.MessageReadBean;
import tongwentongshu.com.app.bean.PioBean;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.contract.MapMainContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.db.DataKeeper;
import tongwentongshu.com.app.map.ClusterControl;
import tongwentongshu.com.app.map.LocationOnSuccess;
import tongwentongshu.com.app.map.MapLocation;
import tongwentongshu.com.app.presenter.MapMainPresenter;
import tongwentongshu.com.app.update.DownLoad;
import tongwentongshu.com.app.utils.NetUtils;
import tongwentongshu.com.app.utils.SpUtils;
import tongwentongshu.com.app.utils.VersionUpdataUtil;
import tongwentongshu.com.app.wxapi.Constants;
import tongwentongshu.com.app.zxing.CaptureActivity;

import static tongwentongshu.com.app.App.EXTRA_BUNDLE;

public class MapMainActivity extends BaseActivity implements MapMainContract.View, AMap.OnMapLoadedListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.title_iv_person)
    ImageView btnPerson;//个人中心
    @BindView(R.id.title_iv_msg)
    ImageView btnMsg;//信息
    @BindView(R.id.title_iv_search)
    ImageView btnSearch;//搜索
    @BindView(R.id.iv_red_dot)
    ImageView red_dot;//消息红色小点


    //地图控件不能通过BindView得到
    private MapView mapView;

    private MapMainPresenter mapMainPresenter;
    private AMap aMap;
    private ClusterControl mClusterControl;
    private MainBooksAdapter pullToRefreshAdapter;
    private MapLocation mapLocation;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_map_main;
    }

    @Override
    protected int getTitleId() {
        return R.string.app_name;
    }


    @Override
    protected void initBundle(Bundle bundle) {
        // 此方法必须重写
        mapView.onCreate(bundle);
    }

    @Override
    protected void initView() {
        messageInit();
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        api.registerApp(Constants.APP_ID);
        mapMainPresenter = new MapMainPresenter(this);

        mapView = (MapView) findViewById(R.id.map);
        checkUpdate();  //自动检查版本
//        Log.e(TAG, "tokenD=" + tokenD + "\ntoken=" + Cache.getToken() + "\nisLogin=" + Cache.getUser().isLogin());
    }

    /**
     * args.putString("is_auth", is_auth);
     * 检查是否为通知打开
     */
    public void messageInit() {
        Bundle bundle = getIntent().getBundleExtra(EXTRA_BUNDLE);
        Log.e("无数据", "bundle.getString(\"book_id\")");
        if (bundle != null) {
            Log.e("有数据", bundle.getString("book_id"));
            MessageEvent result = new MessageEvent(
                    bundle.getString("book_id"),
                    bundle.getString("messurl"),
                    bundle.getString("messid"),
                    bundle.getString("message_style"),
                    bundle.getString("is_auth"));
            if (result.getMessage_style().equals("1")) {
                Bundle b = new Bundle();
                b.putBoolean("pager_Judge", false);
                b.putString("pagerType", "1");
                b.putString("bookId", result.getBook_id());
                startActivity(ReadingDetailsActivity.class, b);
            } else if (result.getMessage_style().equals("2")) {
                startActivity(ShudouActivity.class);
            } else if (result.getMessage_style().equals("3")) {
                startActivity(DepositDetailsActivity.class);
            } else if (result.getMessage_style().equals("4")) {
                Bundle b = new Bundle();
                if (result.getIs_auth().equals("1")) {
                    b.putBoolean("pager_Judge", true);
                } else {
                    b.putBoolean("pager_Judge", false);
                }
                b.putString("pagerType", "1");
                b.putString("bookId", result.getBook_id());
                startActivity(ReadingDetailsActivity.class, b);

            } else {
                Bundle b = new Bundle();
                b.putString("url", result.getMessurl());
                startActivity(WebViewActivity.class, b);

            }
            chengeMessage(result.getMessid());
        }

    }

    /**
     * 检查版本
     */
    public void checkUpdate() {
        if (VersionUpdataUtil.GetNetype(getBaseContext()) == -1) {  //判断网络状态
            Toast.makeText(getBaseContext(), "网络断开了，请检查网络", Toast.LENGTH_SHORT).show();
        } else {
            DownLoad update = new DownLoad(mContext);  //开始下载
            update.checkVersion();
        }
    }

    @Override
    protected void initData() {
        if (Cache.getUser().isLogin())
            initMSG();
    }

    @Override
    protected void initListener() {
        super.initListener();
        if (aMap == null) {
            aMap = mapView.getMap();
            mapMainPresenter.initMap(aMap, mContext);
        }
        // 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setOnMapLoadedListener(this);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        if (Cache.getUser().isLogin() && !TextUtils.isEmpty(Cache.getToken()))
            mapMainPresenter.intiMessage(this);
        Log.i(TAG, "onResume:");
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        dismiss();
        Log.i(TAG, "onPause: ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "onRestart: ");
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mClusterControl)
            mClusterControl.onDestroy();
        mapView.onDestroy();
//        DataKeeper.clear(mContext, LoginUser.class);
//        Cache.clear();
    }

    private PioBean pioBean;

    @Override
    public void onSuccess(PioBean pioBean) {
        this.pioBean = pioBean;
        mClusterControl = new ClusterControl(aMap, pioBean, getApplicationContext(), this);
    }

    boolean logined = false;

    @Override
    public void onLoginSuccess() {
        logined = true;
        mapMainPresenter.intiMessage(this);
    }

    @Override
    public void onSuccess(MessageReadBean bean) {
        Log.e("MessageReadBean", "you");
        DataKeeper.keepSerializable(mContext, bean);
        if (bean.getData().getIs_system() == 1 || bean.getData().getIs_interaction() == 1)
            red_dot.setVisibility(View.VISIBLE);
        else
            red_dot.setVisibility(View.GONE);
    }

    @Override
    public void onSuccess(BookListBean bookListBean) {
        setAdapter(bookListBean);
    }

    @Override
    public void setHierarchy(int hierarchy) {
        this.Hierarchy = hierarchy;
    }

    String Adname = "";
    private String aoiid = "";
    private int Hierarchy = 1;//层级
    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        // marker 对象被点击时回调的接口
        // 返回 true 则表示接口已响应事件，否则返回false
        @Override
        public boolean onMarkerClick(Marker marker) {
            Log.e("Hierarchy", "Hierarchy=" + Hierarchy);
            PioBean.DataBean.AreaarrayBean dis = (PioBean.DataBean.AreaarrayBean) marker.getObject();
            PioBean.DataBean.AreaarrayBean d = getSumBigDis(dis);
            float series = 0;//比例
            switch (Hierarchy) {
                case 1:
                    series = 13.1f;
                    break;
                case 2:
                    series = 17.1f;
                    break;
                case 3:
                    aoiid = dis.getId();
                    Adname = dis.getAdname() + "藏书";
                    initBooksDialog(dis.getAdname() + "藏书" + dis.getBook_num() + "本");
                    return true;
            }

            aMap.animateCamera(CameraUpdateFactory.newCameraPosition(
                    new CameraPosition(new LatLng(Double.valueOf(d.getLatitude()), Double.valueOf(d.getLongitude())), series, 0, 0)), 400, null);
            return true;//返回:true 表示点击marker 后marker 不会移动到地图中心；返回false 表示点击marker 后marker 会自动移动到地图中心
        }
    };

    private PioBean.DataBean.AreaarrayBean getSumBigDis(PioBean.DataBean.AreaarrayBean diss) {
        PioBean.DataBean.AreaarrayBean dis = null;
        if (Hierarchy == 1) {
            for (PioBean.DataBean.AreaarrayBean di : pioBean.getData().getTradingarray()) {
                if (di.getPid().equals(diss.getId())) {
                    if (dis == null) {
                        dis = di;
                    } else {
                        if (Integer.valueOf(dis.getBook_num()) < Integer.valueOf(di.getBook_num()))
                            dis = di;
                    }
                }
            }
        } else if (Hierarchy == 2) {
            for (PioBean.DataBean.AreaarrayBean di : pioBean.getData().getAoiarray()) {
                if (di.getPid().equals(diss.getId())) {
                    if (dis == null) {
                        dis = di;
                    } else {
                        if (Integer.valueOf(dis.getBook_num()) < Integer.valueOf(di.getBook_num()))
                            dis = di;
                    }
                }
            }
        }
        return dis;
    }

    @Override
    public void onMapLoaded() {
        aMap.moveCamera(CameraUpdateFactory.zoomTo(13));

        mapLocation = new MapLocation(this);
        mapLocation.toLocation(locationOnSuccess);
    }


    //定位完毕回调
    public LocationOnSuccess locationOnSuccess = new LocationOnSuccess() {
        @Override
        public void onLocation(AMapLocation location) {
            if (null != location) {
                SpUtils.setString(mContext, Cache.LAT, String.valueOf(location.getLatitude()));
                SpUtils.setString(mContext, Cache.LON, String.valueOf(location.getLongitude()));
                SpUtils.setString(mContext, Cache.ADDRESS, location.getAddress());
                aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(location.getLatitude(), location.getLongitude()), 17.1f, 0, 0)), 800, null);
                String tokenD = PushAgent.getInstance(mContext).getRegistrationId();
                Cache.getUser().setLogin(false);
                mapMainPresenter.login(mContext, tokenD);
                mapMainPresenter.intiBooks(MapMainActivity.this);
            }
        }
    };

    @OnClick({R.id.title_iv_person, R.id.title_iv_search, R.id.title_iv_msg, R.id.btn_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_iv_person:
                if (Cache.LoginVer(mContext))
                    return;
                startActivity(PersonalCenterActivity.class);

                break;
            case R.id.title_iv_search:
                startActivity(SearchActivity.class);
                break;
            case R.id.title_iv_msg:
                if (Cache.LoginVer(mContext))
                    return;
                checkIM(new CallBackColonyContract.OnCheck() {
                    @Override
                    public void check() {
                        startActivity(HomeActivity.class);
                    }
                });

//                initMSG();

//                startActivity(ReadingDetailsActivity.class);
                break;
            case R.id.btn_share:
                startCamera(Manifest.permission.CAMERA);
//                startActivity(ShareBookActivity.class);
                break;
        }
    }

    public static final int request_camera = 100;

    private void startCamera(String permission) {
        if (ContextCompat.checkSelfPermission(MapMainActivity.this, permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MapMainActivity.this, permission)) {
                Toast.makeText(mContext, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(MapMainActivity.this, new String[]{permission},
                        request_camera);
            }
        } else {
            Bundle b = new Bundle();
            b.putBoolean("source", true);//true是从首页进入，false是从分享页进入
            startActivity(CaptureActivity.class, b);
        }
    }

    @Override
    public void onRefresh() {
        onRefreshJudge = true;
//        pullToRefreshAdapter.setEnableLoadMore(false);
        mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "");
    }

    @Override
    public void onLoadMoreRequested() {
        pullToRefreshAdapter.loadMoreEnd(true);
//        onLoadMoreJudge = true;
//        mSwipeRefreshLayout.setEnabled(false);

    }

    public AlertDialog alertDialog;
    public AlertDialog statusAlertDialog;
    TextView type;//书籍状态
    TextView info;//aoi信息
    RelativeLayout type_option;//状态选项
    RelativeLayout show_status;//显示筛选选项
    RecyclerView mRecyclerView;
    SwipeRefreshLayout mSwipeRefreshLayout;
    private RadioGroup mRadioGroup;

    /**
     * 底部弹出书籍列表
     *
     * @return
     */
    public AlertDialog initBooksDialog(String infoString) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.menu_books_list, null);
        type = (TextView) view.findViewById(R.id.tv_read_type);
        info = (TextView) view.findViewById(R.id.tv_main_info);
        info.setText(infoString);
        show_status = (RelativeLayout) view.findViewById(R.id.rel_show_status);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeLayout);
        show_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectStatus();
            }
        });
        if (pullToRefreshAdapter == null) {
            onRefreshJudge = true;
            mSwipeRefreshLayout.setOnRefreshListener(this);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            List arr = new ArrayList<BookListBean.DataBean>();
            pullToRefreshAdapter = new MainBooksAdapter(mContext, arr);
            pullToRefreshAdapter.setOnLoadMoreListener(this, mRecyclerView);
            pullToRefreshAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
            //pullToRefreshAdapter.setPreLoadNumber(3);
            mRecyclerView.setAdapter(pullToRefreshAdapter);

            mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
                @Override
                public void onSimpleItemClick(final BaseQuickAdapter adapter, final View view, final int position) {
//                    Toast.makeText(mContext, Integer.toString(position), Toast.LENGTH_SHORT).show();
                    Bundle b = new Bundle();
                    b.putBoolean("pager_Judge", true);
                    b.putString("pagerType", "1");
                    b.putString("bookId", bookListBean.getData().get(position).getBook_id());
                    startActivity(ReadingDetailsActivity.class, b);
                    alertDialog.dismiss();
                }
            });

            alertDialog = new AlertDialog.Builder(mContext, R.style.dialog_).create();
//            alertDialog.setCancelable(true);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    dismiss();
                }
            });
            alertDialog.show();
            WindowManager.LayoutParams params = alertDialog.getWindow()
                    .getAttributes();
            params.width = (int) NetUtils.getDisplayMetrics((Activity) mContext, NetUtils.DM_WIDTH);

            params.height = NetUtils.dip2px(mContext, 400);
            params.gravity = Gravity.BOTTOM;
            Window window = alertDialog.getWindow();
            window.setWindowAnimations(R.style.menu_animation);
            window.setAttributes(params);
            window.setContentView(view);
            alertDialog.getWindow().setContentView(view);
            mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "");
        }


        return alertDialog;
    }

    BookListBean bookListBean;

    void setAdapter(BookListBean bookListBean) {

        this.bookListBean = bookListBean;
        View empty = getLayoutInflater().inflate(R.layout.empty_no_data, (ViewGroup) mRecyclerView.getParent(), false);
        pullToRefreshAdapter.setEmptyView(empty);
        if (bookListBean.getData() != null && bookListBean.getData().size() > 0) {
            Log.e(TAG, "size_" + bookListBean.getData().size());
            info.setText(Adname + bookListBean.getData().size() + "本");
            if (onRefreshJudge) {
                Log.e(TAG, "onRefreshJudge: " + onRefreshJudge);
                pullToRefreshAdapter.setNewData(bookListBean.getData());
                mSwipeRefreshLayout.setRefreshing(false);
                pullToRefreshAdapter.setEnableLoadMore(true);
                onRefreshJudge = false;
            }
        } else {
            info.setText(Adname + "0本");
            Log.e(TAG, "size_" + bookListBean.getData().size());
            List<BookListBean.DataBean> list = new ArrayList<>();
            pullToRefreshAdapter.setNewData(list);
            mSwipeRefreshLayout.setRefreshing(false);
            pullToRefreshAdapter.setEnableLoadMore(true);
            onRefreshJudge = false;
        }
    }

    private void dismiss() {
        pullToRefreshAdapter = null;
    }

    /**
     * 底部弹出书籍列表
     *
     * @return
     */
    public AlertDialog showSelectStatus() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.menu_status, null);
        mRadioGroup = (RadioGroup) view.findViewById(R.id.rp_status);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                onRefreshJudge = true;
                switch (checkedId) {
                    case R.id.tv_whole:
                        mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "");
                        statusAlertDialog.dismiss();
                        break;
                    case R.id.tv_free:
                        mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "3");
                        statusAlertDialog.dismiss();
                        break;
                    case R.id.tv_reading:
                        mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "2");
                        statusAlertDialog.dismiss();
                        break;
                    case R.id.tv_appointment:
                        mapMainPresenter.intiBooksList(MapMainActivity.this, aoiid, "1");
                        statusAlertDialog.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
        statusAlertDialog = new AlertDialog.Builder(mContext, R.style.dialog_).create();
        statusAlertDialog.show();
        WindowManager.LayoutParams params = statusAlertDialog.getWindow()
                .getAttributes();
        params.width = NetUtils.dip2px(mContext, 80);
//        params.width = (int) NetUtils.getDisplayMetrics((Activity) mContext, NetUtils.DM_WIDTH);
        params.height = NetUtils.dip2px(mContext, 120);
        params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
//        int height = (int) NetUtils.getDisplayMetrics((Activity) mContext, NetUtils.DM_WIDTH);

        params.x = NetUtils.dip2px(mContext, 6);
        params.y = NetUtils.dip2px(mContext, 250);
        Window window = statusAlertDialog.getWindow();
        window.setWindowAnimations(R.style.TRM_ANIM_STYLE);
        window.setAttributes(params);
        window.setContentView(view);
        statusAlertDialog.getWindow().setContentView(view);


        return statusAlertDialog;
    }

}
